// pages/product-setting/com-select-data/index.js
Component({
  /**
   * 组件的属性列表
   */
  options: {
    pureDataPattern: /^_/
  },
  properties: {
    show: {
      type: Boolean,
      value: false
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    dataSource: [],
    name: '',
    _tempData: {}
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onClose() {
      this.triggerEvent('close');
    },
    onAdd() {
      const dataSource = this.data.dataSource;
      dataSource.push({
        name: dataSource.length,
        value: ''
      })
      this.setData({
        dataSource
      })
    },
    onChange(event){
      const dataSource = this.data.dataSource,
      {
        index
      } = event.currentTarget.dataset,
      value = event.detail;
      dataSource[index].value = value;
      this.setData({
        dataSource
      })
    },
    ontap(event){
      const dataSource = this.data.dataSource,
      {
        index,
        title
      } = event.currentTarget.dataset;
      wx.showModal({
         editable: true,
         placeholderText: '输入',
         title,
         content: dataSource[index]['value'],
         success: res=>{
           if(res.confirm){
             dataSource[index]['value'] = res.content;
             this.setData({
               dataSource
             })
           }
         }
      })
    },
    onRemove(event) {
      const index = event.currentTarget.dataset.index;
      const dataSource = this.data.dataSource;
      dataSource.splice(index, 1);
      this.setData({
        dataSource
      })
    },
    onSubmit(event) {
      const value = event.detail.value;
      const valid = Object.values(value).every(it => !!it);
      if (valid) {
        this.triggerEvent('finish', {
          data: Object.values(value),
          tempData: this.data._tempData
        });
      } else {
        wx.showToast({
          title: '存在未填项',
          icon: 'error'
        })
      }
    },
    setSource(name, data, tempData) {
      const dataSource = data?.map((it, index) => {
        return {
          name: index,
          value: it
        }
      });
      this.setData({
        name,
        dataSource: dataSource || [],
        _tempData: tempData
      })
    }
  }
})